package com.java110.mall.cart.cmd.storeOrder;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.dto.distributionMode.DistributionModeDto;
import com.java110.dto.file.FileRelDto;
import com.java110.dto.product.ProductDto;
import com.java110.dto.shop.ShopConfigDto;
import com.java110.dto.vipUser.ShopVipUserDto;
import com.java110.dto.storeOrder.ResultComputeStoreOrderGoodsDto;
import com.java110.dto.storeOrder.ResultComputeStoreOrderPriceDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.cart.IStoreCartInnerServiceSMO;
import com.java110.intf.shop.IShopConfigV1InnerServiceSMO;
import com.java110.intf.system.IFileRelInnerServiceSMO;
import com.java110.intf.goods.IDistributionModeInnerServiceSMO;
import com.java110.intf.goods.IProductInnerServiceSMO;
import com.java110.intf.shop.IShopVipUserInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.utils.cache.MappingCache;
import com.java110.utils.constant.MappingConstant;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单价格计算功能
 */
@Java110Cmd(serviceCode = "storeOrder.computeStoreOrderPrice")
public class ComputeStoreOrderPriceCmd extends Cmd {

    public static final int USER_FLAG_NOBODY = 1; // 游客
    public static final int USER_FLAG_VIP = 2; // vip
    public static final int USER_FLAG_OWNER = 3; // 业主
    public static final int USER_FLAG_VIP_OWNER = 4; //业主也是vip


    @Autowired
    private IStoreCartInnerServiceSMO storeCartInnerServiceSMOImpl;

    @Autowired
    private IProductInnerServiceSMO productInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userInnerServiceSMOImpl;

//    @Autowired
//    private IOwnerInnerServiceSMO ownerInnerServiceSMOImpl;

    @Autowired
    private IShopVipUserInnerServiceSMO shopVipUserInnerServiceSMOImpl;

    @Autowired
    private IDistributionModeInnerServiceSMO distributionModeInnerServiceSMOImpl;

    @Autowired
    private IFileRelInnerServiceSMO fileRelInnerServiceSMOImpl;

    @Autowired
    private IShopConfigV1InnerServiceSMO shopConfigV1InnerServiceSMOImpl;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {

        Assert.hasKeyAndValue(reqJson, "shopId", "未包含商铺信息");
        Assert.hasKeyAndValue(reqJson, "cartType", "未包含购物车类型");
        Assert.hasKeyAndValue(reqJson, "valueId", "未包含商品");
        Assert.hasKeyAndValue(reqJson, "goodsNum", "未包含数量");
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        ResultComputeStoreOrderPriceDto resultComputeStoreOrderPriceDto = null;

        String valueId = reqJson.getString("valueId");
        String goodsNum = reqJson.getString("goodsNum");
        String[] valueIds = valueId.split(",");
        String[] goodsNums = goodsNum.split(",");

        if (valueIds.length != goodsNums.length) {
            throw new CmdException("参数错误,商品和数量不对应");
        }


        ProductDto productDto = new ProductDto();
        productDto.setShopId(reqJson.getString("shopId"));
        productDto.setValueIds(valueIds);
        List<ProductDto> productDtos = productInnerServiceSMOImpl.queryProductAndSpecs(productDto);

        if (ListUtil.isNull(productDtos)) {
            cmdDataFlowContext.setResponseEntity(ResultVo.error("未包含商品"));
            return;
        }

        //查询配送方式
        ShopConfigDto shopConfigDto = new ShopConfigDto();
        shopConfigDto.setShopId(reqJson.getString("shopId"));
        List<ShopConfigDto> shopConfigDtos = shopConfigV1InnerServiceSMOImpl.queryShopConfigs(shopConfigDto);
        String sendWay = DistributionModeDto.MODE_TYPE_USER;
        double sendFee = 0;
        if (!ListUtil.isNull(shopConfigDtos)) {
            sendWay = shopConfigDtos.get(0).getSendWay();
            sendFee = StringUtil.isNumber(shopConfigDtos.get(0).getSendFee()) ? Double.parseDouble(shopConfigDtos.get(0).getSendFee()) : 0;
        }

        // 查询用户角色
        int userFlag = getUserFlag(cmdDataFlowContext, reqJson);
        List<ResultComputeStoreOrderGoodsDto> goodsDtos = new ArrayList<>();
        ResultComputeStoreOrderGoodsDto goodsDto = null;
        BigDecimal totalPayPriceDec = BigDecimal.valueOf(0.0);
        if (DistributionModeDto.MODE_TYPE_STORE.equals(sendWay)) {
            totalPayPriceDec = BigDecimal.valueOf(sendFee);
        }
        BigDecimal deductionDec = BigDecimal.valueOf(0.0);
        for (ProductDto tmpProductDto : productDtos) {
            goodsDto = BeanConvertUtil.covertBean(tmpProductDto, ResultComputeStoreOrderGoodsDto.class);
            goodsDto.setGoodsNum(1.0);
            if (reqJson.containsKey("goodsNum") && StringUtil.isNumber(reqJson.getString("goodsNum"))) {
                goodsDto.setGoodsNum(reqJson.getDouble("goodsNum"));
            }
            for (int vIndex = 0; vIndex < valueIds.length; vIndex++) {
                if (!tmpProductDto.getValueId().equals(valueIds[vIndex])) {
                    continue;
                }
                goodsDto.setGoodsNum(Double.parseDouble(goodsNums[vIndex]));
            }
            goodsDto.setPayPrice(getPayPrice(tmpProductDto, userFlag, goodsDto));

            goodsDto.setExtProdId(tmpProductDto.getExtProdId());
            goodsDto.setExtValueId(tmpProductDto.getExtValueId());
            goodsDto.setCsId(tmpProductDto.getCsId());
            goodsDto.setSuType(tmpProductDto.getSuType());

            String payPriceName = "";
            if (userFlag == USER_FLAG_VIP || userFlag == USER_FLAG_VIP_OWNER) {
                payPriceName = "会员价";
            } else if (userFlag == USER_FLAG_OWNER) {
                payPriceName = "业主价";
            }
            goodsDto.setPayPriceName(payPriceName);

            totalPayPriceDec = totalPayPriceDec.add(BigDecimal.valueOf(goodsDto.getPayPrice()));

            deductionDec = getDeductionDec(deductionDec, tmpProductDto, goodsDto.getGoodsNum());

            goodsDtos.add(goodsDto);
        }

        double totalPayPrice = totalPayPriceDec.setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue();

        List<String> productIds = new ArrayList<>();
        for (ResultComputeStoreOrderGoodsDto tmpProductDto : goodsDtos) {
            productIds.add(tmpProductDto.getProductId());
        }

        FileRelDto fileRelDto = new FileRelDto();
        fileRelDto.setObjIds(productIds.toArray(new String[productIds.size()]));
        fileRelDto.setRelTypeCd(FileRelDto.REL_TYPE_CD_GOODS_COVER);
        List<FileRelDto> fileRelDtos = fileRelInnerServiceSMOImpl.queryFileRels(fileRelDto);

        //刷入图片信息
        List<String> photoVos = null;
        String url = null;
        String imgUrl = MappingCache.getValue(MappingConstant.FILE_DOMAIN, "IMG_PATH");
        imgUrl += (!StringUtil.isEmpty(imgUrl) && imgUrl.endsWith("/") ? "" : "/");
        for (ResultComputeStoreOrderGoodsDto tmpProductDto : goodsDtos) {
            for (FileRelDto tmpFileRelDto : fileRelDtos) {

                if (!tmpProductDto.getProductId().equals(tmpFileRelDto.getObjId())) {
                    continue;
                }
                if (StringUtil.isEmpty(tmpFileRelDto.getFileRealName())) {
                    continue;
                }
                url = imgUrl + tmpFileRelDto.getFileRealName();
                if (tmpFileRelDto.getFileRealName().startsWith("http")) {
                    url = tmpFileRelDto.getFileRealName();
                }
                tmpProductDto.setCoverPhoto(url);

            }
        }


        resultComputeStoreOrderPriceDto = new ResultComputeStoreOrderPriceDto(totalPayPrice, sendWay, sendFee, deductionDec.doubleValue(), goodsDtos);
        if (reqJson.containsKey("vipUserDto")) {
            resultComputeStoreOrderPriceDto.setVipUserDto(reqJson.getObject("vipUserDto", ShopVipUserDto.class));
        }

        cmdDataFlowContext.setResponseEntity(ResultVo.createResponseEntity(resultComputeStoreOrderPriceDto));
    }


    private BigDecimal getDeductionDec(BigDecimal deductionDec, ProductDto tmpProductDto, double goodsNum) {
        BigDecimal goodsDeductionDec = new BigDecimal(tmpProductDto.getDefaultSpecValue().getDeduction());
        goodsDeductionDec = goodsDeductionDec.multiply(BigDecimal.valueOf(goodsNum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        deductionDec = deductionDec.add(goodsDeductionDec);
        return deductionDec;
    }

    private DistributionModeDto getShopDistributionMode(String shopId) {
        DistributionModeDto distributionModeDto = new DistributionModeDto();
        distributionModeDto.setShopId(shopId);
        List<DistributionModeDto> shopDistributionModeDtos = distributionModeInnerServiceSMOImpl.queryDistributionModes(distributionModeDto);
        if (shopDistributionModeDtos == null || shopDistributionModeDtos.size() < 1) {
            return null;
        }
        return shopDistributionModeDtos.get(0);
    }

    /**
     * 计算 支付价格
     *
     * @param tmpProductDto
     * @param userFlag
     * @return
     */
    private double getPayPrice(ProductDto tmpProductDto, int userFlag, ResultComputeStoreOrderGoodsDto goodsDto) {

        double payPrice = Double.parseDouble(tmpProductDto.getDefaultSpecValue().getPrice());
        if (userFlag == USER_FLAG_VIP || userFlag == USER_FLAG_VIP_OWNER) {
            payPrice = Double.parseDouble(tmpProductDto.getDefaultSpecValue().getVipPrice());
        } else if (userFlag == USER_FLAG_OWNER) {
            payPrice = Double.parseDouble(tmpProductDto.getDefaultSpecValue().getOwnerPrice());
        }

        //todo 判断是不是秒杀商品


        payPrice = BigDecimal.valueOf(goodsDto.getGoodsNum()).multiply(BigDecimal.valueOf(payPrice)).setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue();

        return payPrice;
    }

    public int getUserFlag(ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) {
        //查询用户信息
        int userFlag = USER_FLAG_NOBODY;
        UserDto userDto = new UserDto();
        userDto.setUserId(cmdDataFlowContext.getReqHeaders().get("user-id"));
        userDto.setPage(1);
        userDto.setRow(1);
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);
        if (userDtos == null || userDtos.size() < 1) {
            return userFlag;
        }

        String tel = userDtos.get(0).getTel();

        //
//        OwnerDto ownerDto = new OwnerDto();
//        ownerDto.setLink(tel);
//        int ownerCount = ownerInnerServiceSMOImpl.queryOwnersCount(ownerDto);
//        if (ownerCount > 0) {
//            userFlag = USER_FLAG_OWNER;
//        }
//
//        ShopVipUserDto shopVipUserDto = new ShopVipUserDto();
//        shopVipUserDto.setShopId(reqJson.getString("shopId"));
//        shopVipUserDto.setVipTel(tel);
//        shopVipUserDto.setPage(1);
//        shopVipUserDto.setRow(1);
//        List<ShopVipUserDto> shopVipUserDtos = shopVipUserInnerServiceSMOImpl.queryShopVipUsers(shopVipUserDto);
//        if (shopVipUserDtos != null && shopVipUserDtos.size() > 0) {
//            if (userFlag == USER_FLAG_OWNER) {
//                userFlag = USER_FLAG_VIP_OWNER;
//            } else {
//                userFlag = USER_FLAG_VIP;
//            }
//            reqJson.put("vipUserDto", shopVipUserDtos.get(0));
//        }

        return userFlag;

    }
}
